//
//  CSSTabBar.swift
//  weibo28
//
//  Created by chushushan on 16/5/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

//使用代理实现点击事件的传递
//protocol CSSTabBarDelegate: NSObjectProtocol {
//
//    func didSelectedComposeButton()
//}


class CSSTabBar: UITabBar {
    //设置代理属性
//    weak var cssDelegate: CSSTabBarDelegate?
    
    //设置闭包
    var composeButtonClousre: (() -> ())?
    
        private lazy var composeButton: UIButton = {
    
        let button = UIButton()
            
            button.addTarget(self, action: "composeButtonClick", forControlEvents: .TouchUpInside)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        //设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        button.sizeToFit()
        return button
    
    }()
    
    //手写代码形式去创建对象，不支持xib/storyboard
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    //使用xib或者storyboard创建视图的时候会执行
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    //支持xib的时候
//    super.init(coder: aDecoder)
//        setupUI()
    }
    
    
    private func setupUI() {
    
    addSubview(composeButton)
    }
    
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        composeButton.center.x = frame.size.width * 0.5
        composeButton.center.y = frame.size.height * 0.5
        
        //计算子视图按钮大小
        let itemWidth = frame.size.width / 5
        //记录当前遍历到第几个button
        var index = 0
        
        
        for childView in subviews {
        
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
            childView.frame.size.width = itemWidth
            childView.frame.origin.x = CGFloat(index) * itemWidth
            
                index++
                
                //第三个子视图按钮之后，需要多加一个
                if index == 2 {
                index++
                }
            }
        
        }
        
    }
    
    
    @objc private func composeButtonClick() {
     print("nishi")
        
        //执行闭包
        composeButtonClousre?()
        //代理对象调用方法
//        cssDelegate?.didSelectedComposeButton()
    }
    
    
    
    
    
    
    

}




















